package com.yvon.maple.service.auth.authentication.ldap;

import com.yvon.maple.service.auth.service.SecurityUserService;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author : Yvon
 * @since : 2022-02-17
 */
@Data
public class LdapAuthenticationProvider implements AuthenticationProvider {

    private final SecurityUserService securityUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        LdapAuthenticationToken authenticationToken = (LdapAuthenticationToken) authentication;
        UserDetails user = securityUserService.loadUserByLdap((String) authenticationToken.getPrincipal(), (String) authenticationToken.getCredentials());
        LdapAuthenticationToken authenticationResult = new LdapAuthenticationToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return LdapAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
